<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { login } from '../store.js'

const router = useRouter()
const username = ref('')
const email = ref('')
const password = ref('')
const confirmPassword = ref('')
const errorMessage = ref('')
const successMessage = ref('')
const isLoading = ref(false)

const handleRegister = async () => {
  // 简单表单验证
  if (!username.value || !email.value || !password.value || !confirmPassword.value) {
    errorMessage.value = '请填写所有必填字段'
    return
  }

  if (password.value !== confirmPassword.value) {
    errorMessage.value = '两次输入的密码不一致'
    return
  }

  if (password.value.length < 6) {
    errorMessage.value = '密码长度不能少于6位'
    return
  }

  // 简单的邮箱格式验证
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!emailRegex.test(email.value)) {
    errorMessage.value = '请输入有效的邮箱地址'
    return
  }

  isLoading.value = true
  errorMessage.value = ''
  successMessage.value = ''

  try {
    // 创建新用户
    const newUser = {
      id: Math.random().toString(36).substr(2, 9),
      username: username.value,
      email: email.value,
      password: password.value, // 实际项目中应该加密存储密码
      avatar: `https://picsum.photos/200/200?random=${Math.floor(Math.random() * 100)}`,
      bio: '',
      following: 0,
      followers: 0,
      joinDate: new Date().toISOString()
    }
    
    // 获取现有的用户列表，如果不存在则创建
    let users = JSON.parse(localStorage.getItem('users')) || []
    
    // 检查用户名是否已存在
    const existingUser = users.find(user => user.username === username.value)
    if (existingUser) {
      errorMessage.value = '用户名已存在'
      isLoading.value = false
      return
    }
    
    // 添加新用户
    users.push(newUser)
    localStorage.setItem('users', JSON.stringify(users))
    
    // 自动登录新用户
    await login({
      username: newUser.username,
      id: newUser.id,
      avatar: newUser.avatar,
      bio: newUser.bio,
      following: newUser.following,
      followers: newUser.followers
    })
    
    // 注册成功后跳转到个人主页
    router.push('/profile')
  } catch (error) {
    errorMessage.value = '注册失败，请稍后重试'
    console.error('Register failed:', error)
  } finally {
    isLoading.value = false
  }
}

const goToLogin = () => {
  router.push('/login')
}

const handleAuthRedirect = () => {
  router.push('/auth')
}
</script>

<template>
  <div class="register-container">
    <div class="register-header">
      <div class="logo">
        <svg width="60" height="60" viewBox="0 0 40 40" fill="none">
          <rect width="40" height="40" rx="8" fill="#ff8c00"/>
          <text x="20" y="26" text-anchor="middle" fill="white" font-size="18" font-weight="bold">问答社区</text>
        </svg>
      </div>
      <h1>注册问答社区</h1>
      <p>加入我们，共同成长</p>
    </div>
    
    <div class="register-box">
      <form @submit.prevent="handleRegister">
        <div class="form-group">
          <input
            v-model="username"
            type="text"
            placeholder="请设置用户名"
            required
            :disabled="isLoading"
            class="input"
          />
        </div>
        <div class="form-group">
          <input
            v-model="email"
            type="email"
            placeholder="请输入邮箱地址"
            required
            :disabled="isLoading"
            class="input"
          />
        </div>
        <div class="form-group">
          <input
            v-model="password"
            type="password"
            placeholder="请设置密码"
            required
            :disabled="isLoading"
            class="input"
          />
        </div>
        <div class="form-group">
          <input
            v-model="confirmPassword"
            type="password"
            placeholder="请确认密码"
            required
            :disabled="isLoading"
            class="input"
          />
        </div>
        
        <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
        <p v-if="successMessage" class="success-message">{{ successMessage }}</p>
        
        <button
          type="submit"
          class="register-btn"
          :disabled="isLoading"
        >
          {{ isLoading ? '注册中...' : '立即注册' }}
        </button>
      </form>
      
      <div class="login-link">
        已有账号？
        <button type="button" @click="goToLogin" class="login-btn">
          立即登录
        </button>
      </div>
      
      <div class="register-agreement">
        注册即表示您同意小红书的
        <a href="#" class="link">用户协议</a>
        和
        <a href="#" class="link">隐私政策</a>
      </div>
    </div>
  </div>
</template>

<style scoped>
.register-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  padding: 20px;
  background-color: var(--vt-c-yellow-light);
}

.register-header {
  text-align: center;
  margin-bottom: 40px;
}

.register-header .logo {
  margin-bottom: 16px;
}

.register-header h1 {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.register-header p {
  font-size: 16px;
  color: #999;
}

.register-box {
  width: 100%;
  max-width: 400px;
  background-color: #fff;
  border-radius: 16px;
  padding: 32px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.form-group {
  margin-bottom: 20px;
}

.input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.input:focus {
  outline: none;
  border-color: #ff8c00;
}

.error-message {
  color: #ff8c00;
  font-size: 14px;
  margin-bottom: 16px;
  text-align: center;
}

.success-message {
  color: #07C160;
  font-size: 14px;
  margin-bottom: 16px;
  text-align: center;
}

.register-btn {
  width: 100%;
  padding: 12px;
  background-color: #ff8c00;
  color: white;
  border: none;
  border-radius: 24px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
}

.register-btn:hover:not(:disabled) {
  background-color: #e07a00;
}

.register-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.login-link {
  margin-top: 24px;
  text-align: center;
  color: #999;
  font-size: 14px;
}

.login-btn {
  color: #ff8c00;
  background: none;
  border: none;
  font-size: 14px;
  cursor: pointer;
  font-weight: 500;
}

.register-agreement {
  margin-top: 20px;
  text-align: center;
  color: #ccc;
  font-size: 12px;
}

.register-agreement .link {
  color: #ff8c00;
  text-decoration: none;
}

@media (max-width: 480px) {
  .register-box {
    padding: 24px;
  }
}
</style>